package org.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfiguration {
    @Autowired
    public void configurer(AuthenticationManagerBuilder
                                   authenticationManagerBuilder) throws Exception {
      BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
 String enpassword1 = encoder.encode("111111");
System.out.println(enpassword1);
String enpassword2 = encoder.encode("222222");
System.out.println(enpassword2);
//先使用内存认证方式 用户名是lisi passwordEncoder密码加密方式是
//        BCryptPasswordEncoder 密码用22222 用户的授权角色是vip
authenticationManagerBuilder
 .inMemoryAuthentication().
 passwordEncoder(encoder).
 withUser("lisi").
 password(enpassword2).
 roles("vip");
authenticationManagerBuilder
  .inMemoryAuthentication().
 passwordEncoder(encoder).
 withUser("zhangsan").
 password(enpassword1).
 roles("common");}
//先使用内存认证方式 用户名是lisi passwordEncoder密码加密方式是
//    BCryptPasswordEncoder 密码用11111 用户的授权角色是common
//授权
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
 // //过滤请求下面两个名称要一致
 httpSecurity.authorizeHttpRequests(authorize -> {
  authorize.requestMatchers("/",
                    "/login", "/detail/common/*",
                    "/login/**").permitAll();//不需要认证和授权
 authorize.requestMatchers("/detail/vip/*") //vip用户必须登录和授权
//            如果非vip权限授权的用户 访问 vip资源 security 反馈出403
 .hasAnyRole("vip")//授权
  .anyRequest() //任何请求
  .authenticated();//先认证（登录）
 })
//自定义页面
  .formLogin(form ->
                form
//登陆访问路径：提交表单之后跳转的地址,可以看作一个中转站，个步骤就是验证user的一个过程
 .loginProcessingUrl("/userLogin")
 .usernameParameter("name")
 .passwordParameter("pwd")

 .loginPage("/login")
 ///forward 跳转注意:不会跳转到之前请求路径
 .defaultSuccessUrl("/")//登陆成功之后跳转的路径
 .failureForwardUrl("/login")//失败之后的跳转
 );
return httpSecurity.build();
  }
}
